package com.xjj.datarources.utils;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.xjj.datarources.base.DataSources;
import com.xjj.datarources.common.DataTypeEnum;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @name: xjj
 * @date: 2021/5/18 10:49
 */
public class DBUtils {

    private final static Log log = LogFactory.get();


    public static Connection test(DataSources dataSources) {

        //boolean flag = false;


        Connection connection;
        try {
            if (dataSources.getDataType() == null){
                throw new RuntimeException("未指导数据库类型");
            }
            if (dataSources.getDataType().equals("mysql")){
                Class.forName(DataTypeEnum.ORACLE.getDataDriver()).newInstance();

            }else if (dataSources.getDataType().equals("oracle")){
                Class.forName(DataTypeEnum.MYSQL.getDataDriver()).newInstance();
            }else if (dataSources.getDataType().equals("sqlserver")){
                Class.forName(DataTypeEnum.SQL_SERVER.getDataDriver()).newInstance();
            }
            connection = DriverManager.getConnection(dataSources.getUrl(), dataSources.getUsername(), dataSources.getPassword());
            //flag = true;
        }catch (Exception e){
            log.error("错误", e);
            throw new RuntimeException("数据库连接失败");

        }

        return connection;
    }


    public boolean connIsOk(Connection conn) throws SQLException {
        return null != conn && !conn.isClosed();
    }

    public void closeConn(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }






}
